<template>
    <div class="bgn">
        <div class="login">
            <el-form class="login-form" ref="loginForm" :rules="loginRules" :model="loginForm" label-width="0px">
                <div class="login-item" style="color: #409eff;font-size: 25px;font-weight: bold;">丁昌江rbac管理系统</div>

                <el-form-item class="login-item" prop="username">
                    <el-input @keydown.enter.native="login" prefix-icon="el-icon-user" placeholder="用户名"
                              v-model="loginForm.username"></el-input>
                </el-form-item>

                <el-form-item class="login-item" prop="password">
                    <el-tooltip placement="left" popper-class="mypopper">
                        <div slot="content">密码规则提示：<br/>密码首字母必须大写
                            <br/>大小写字母、数字、特殊字符四选三
                            <br/>长度：8-16位
                        </div>
                        <el-input @keydown.enter.native="login" :type="flag?'text':'password'"
                                  prefix-icon="el-icon-unlock"
                                  placeholder="密码"
                                  v-model="loginForm.password">
                            <i slot="suffix" :class="flag?'iconfont icon-yanjing':'iconfont icon-yanjing_bi'"
                               @click="flag=!flag"/>
                        </el-input>
                    </el-tooltip>
                </el-form-item>

                <el-form-item class="login-item captcha-item" prop="captcha">
                    <el-input @keydown.enter.native="login" prefix-icon="iconfont icon-yanzhengma" placeholder="验证码"
                              v-model="loginForm.captcha"/>
                    <img @click="refreshCaptcha" style="margin-left: 5px" :src="imgUrl" alt="验证码" width="100px" height="40px"/>
                </el-form-item>

                <el-button @click="login" type="primary" round style="width: 100px;">登录</el-button>
            </el-form>

            <div class="introduce">
                <h2>技术栈</h2>
                <h5>springboot</h5>
                <h5>springsecurity</h5>
                <h5>mybatisplus</h5>
                <h5>jwt</h5>
                <h5>vue+element-ui</h5>
            </div>
        </div>
    </div>

</template>

<!--不想在输入界面触发rules的做法，在el-input组件中加入-->
<!--:validate-event="false"-->

<script>
import sessionApi from "../api/sessionApi";
import vuexApi from "../api/vuexApi"
import {resetRouter} from "@/router";
export default {
    name: "Login",
    data() {
        let validateCaptcha = (rule, value, callback) => {
            switch (this.captchaResult) {
                case 603:
                    callback(new Error('验证码错误，请重新输入'));
                    this.$axiosApi.getImg("/captcha/getCaptcha", (imgUrl) => {
                        this.imgUrl = imgUrl
                    });
                    break;
                case 604:
                    callback(new Error('验证图片过期，已重新加载验证图片'));
                    this.$axiosApi.getImg("/captcha/getCaptcha", (imgUrl) => {
                        this.imgUrl = imgUrl
                    });
                    break;
                default:
                    callback()

            }
        }
        let validateUsername = (rule, value, callback) => {
            if (this.captchaResult === 605) {
                this.$axiosApi.getImg("/captcha/getCaptcha", (imgUrl) => {
                    this.imgUrl = imgUrl
                });
                callback(new Error('用户名不存在'));
            }
            callback()
        }
        let validatePassword = (rule, value, callback) => {
            if (this.captchaResult === 606) {
                this.$axiosApi.getImg("/captcha/getCaptcha", (imgUrl) => {
                    this.imgUrl = imgUrl
                });
                callback(new Error('密码错误'));
            }
            callback()
        }

        return {
            flag: false,
            loginForm: {username: 'admin', password: 'Admin123', captcha: ''},
            loginRules: {
                username: [
                    {required: true, message: '请输入用户名'},
                    {validator: validateUsername, trigger: 'blur'}
                ],
                captcha: [
                    {required: true, message: '请输入验证码'},
                    {
                        pattern: /^(-?)\d+$/,
                        message: "验证码只能是数字",
                        trigger: "blur"
                    },
                    {validator: validateCaptcha, trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '请输入密码'},
                    {
                        pattern: /^[A-Z]((?=.*\d)(?=.*[_!@#$%^&*`~()-+=])|(?=.*\d)(?=.*[a-z])|(?=.*[a-z])(?=.*[_!@#$%^&*`~()-+=]))[a-zA-Z0-9_!@#$%^&*`~()-+=]{7,17}$/,
                        message: "密码首字母大写，（字母大小写、数字、特殊字符）四选三，且在8～16位之间",
                        trigger: "blur"
                    },
                    {validator: validatePassword, trigger: 'blur'}
                ],
            },
            imgUrl: '',
            captchaResult: 200
        }
    }
    ,
    created() {

        //重置路由
        resetRouter()
        //session里的登录信息清除
        sessionApi.logout()

        this.$axiosApi.getImg("/captcha/getCaptcha", (imgUrl) => {
            this.imgUrl = imgUrl
        });
    }
    ,

    methods: {
        refreshCaptcha() {
            this.$axiosApi.getImg("/captcha/getCaptcha", (imgUrl) => {
                this.imgUrl = imgUrl
            });
        },
        login() {
            this.$refs['loginForm'].validate((valid) => {
                if (!valid) {
                    return false
                }
                this.$post("/user/login", this.loginForm).then(({data}) => {

                    this.$message({
                        message: "登录成功",
                        type: "success"
                    });

                    sessionApi.login(data.id,data.username,data.token)

                    console.log(data.menuVoList)

                    vuexApi.putAuthList(data.menuVoList).then(() => {
                        //如果跳转到登录前有携带路径，那么登录成功后，跳转回去
                        const path = this.$route.query.redirect;
                        if (path) {
                            this.$router.push({'path': path});
                        } else {
                            this.$router.push({
                                path: '/'
                            });
                        }
                    })
                    //this.$store.dispatch("putAuthList", data.menuVoList).then(() => {
                    //    //如果跳转到登录前有携带路径，那么登录成功后，跳转回去
                    //    const path = this.$route.query.redirect;
                    //    if (path) {
                    //        this.$router.push({'path': path});
                    //    } else {
                    //        this.$router.push({
                    //            path: '/'
                    //        });
                    //    }
                    //})
                }).catch((res) => {
                    //得到请求错误码，校验规则再根据错误码去展示对应的错误提示
                    this.captchaResult = res.code
                    this.$refs['loginForm'].validate(() => {
                        //验证过后，设置回初始值 captchaResult
                        this.captchaResult = 200
                    })
                });
            })
        }
    }
}
</script>

<style scoped>
.bgn {
    background: url(../assets/img/bg.jpg);
    background-size: 100% 100%;
    height: 100vh;
}

.login {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    box-sizing: border-box;
    display: flex;
}

.login-form {
    padding: 40px 80px;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: space-around;
    background: #ffffff;
    border-radius: 15px 0 0 15px;
}

/*设置输入框下边距*/
.login-form .login-item {
    margin-bottom: 40px;
}

/*设置登录框 input 背景色*/
/deep/ .login-form .el-input__inner {
    background: #f0f0f0 !important;
    border: none !important;
    border-radius: 15px;
    padding-left: 35px !important;
    box-sizing: border-box;
    /*color: black;*/
}

/*给输入框设置宽度*/
.login-form .el-form-item {
    width: 300px;
}

/*验证码输入框与图片设置 begin */
/deep/ .login-form .captcha-item .el-form-item__content {
    width: 300px;
    display: flex;
    align-items: center;
}

/*验证码输入框与图片设置 end */

/*介绍部分*/
.introduce {
    width: 250px;
    background: linear-gradient(to right bottom, #409eff, #6ec3ff);
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
    padding: 120px 0;
    box-sizing: border-box;
    border-radius: 0px 15px 15px 0;
    color: white;
}


</style>
